package cuckoo.ioc.scanner.impl;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

import cuckoo.ioc.scanner.ClassesScanner;
import cuckoo.util.ClassUtil;
import cuckoo.util.PathUtil;

public class FileClassesScanner implements ClassesScanner, FileFilter {

	@Override
	public Set<Class<?>> doScan(String base, URL url) throws IOException {
		return doScan(url.getPath());
	}

	private Set<Class<?>> doScan(String path) throws IOException {
		File f = new File(path);
		if (!f.exists()) {
			return null;
		}

		Set<Class<?>> classes = new HashSet<Class<?>>();
		if (f.isFile()) {
			Class<?> resource = ClassUtil.getClassAsResource(formatClassName(f.getAbsolutePath()));
			if (resource != null)
				classes.add(resource);
			return classes;
		}

		for (File child : f.listFiles(this)) {
			classes.addAll(doScan(child.getAbsolutePath()));
		}

		return classes;
	}

	private String formatClassName(String path) {
		return path.substring(PathUtil.getClassPath().length(), path.length() - 6).replace('\\', '.');
	}

	@Override
	public boolean accept(File pathname) {
		return pathname.isDirectory() || pathname.getName().endsWith(".class");
	}

}
